package org.example.controller;

import com.alibaba.druid.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.JwtHelper;
import org.example.utils.Result;
import org.example.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 宋孟林
 * @description
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtHelper jwtHelper;

    /**
     * 用户登录功能
     * @param user 用户参数
     * @return 返回查找的结果
     */
    @PostMapping("/login")
    public Result<Object> login(@RequestBody User user){
        Result<Object> result = userService.login(user);
        log.info("result is {}", result);
        return result;
    }

    /**
     * 1. 判断token是否过期
     * 2. 通过service来获取userInfo
     * 3. 将userInfo信息封装到结果类中然后返回
     * @param token 1
     * @return 1
     */
    @GetMapping("/getUserInfo")
    public Result<Object> getUserInfo(@RequestHeader String token){
        User userInfo = userService.getUserInfo(token);
        Map<String, Object> map = new HashMap<>();
        map.put("loginUser", userInfo);
        return Result.build(map, ResultCodeEnum.SUCCESS);
    }

    /**
     * 1. 通过service来判断用户名是否存在
     * 2. 如果存在，则返回true，否则返回false
     * @param username 用户名
     * @return 结果
     */
    @PostMapping("/checkUserName")
    public Result<Object> checkUserName(@RequestParam String username){
        boolean flag = userService.checkUserName(username);
        if (flag){
            return Result.build(null, ResultCodeEnum.USERNAME_USED);
        }else {
            return Result.build(null, ResultCodeEnum.SUCCESS);
        }
    }

     @PostMapping("/regist")
     public Result<Object> register(@RequestBody User user){
         return userService.register(user);
     }

     @GetMapping("/checkLogin")
     public Result<Object> checkLogin(@RequestHeader String token){
        if (StringUtils.isEmpty(token) || jwtHelper.isExpiration(token)) {
            return Result.build(null, ResultCodeEnum.NOTLOGIN);
        }
        return Result.build(null, ResultCodeEnum.SUCCESS);
     }
}
